package com.signway.swmediaplayerdemo.view;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.opengl.GLSurfaceView.Renderer;
import android.opengl.GLUtils;
import android.util.Log;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class SignwayOpenGLRender implements Renderer {
	private final String TAG = "SignwayOpenGLRender";
	
	public float textX = 0;
	public float textY = 0;
	public float areaW = 0;
	public float areaH = 0;
	public int textSize = 20;
	public int textColor = 0;//LColor.white;
	public int bgColor = 0;//LColor.black;
	public int alpha = 0;
	public String textContent = "";
	
	public GLDataListener dataListener = null;
	
	//位图  
    private Bitmap bitmap;
    ShortBuffer indices;
    int textureId = 0;
    
    public boolean isStopWork = false;
    
    public SignwayOpenGLRender() {
    	ByteBuffer indicesBuffer = ByteBuffer.allocateDirect(6 * 2);
        indicesBuffer.order(ByteOrder.nativeOrder());
        indices = indicesBuffer.asShortBuffer();  
        indices.put(new short[] { 0, 1, 2, 1, 2, 3});  
          
        indices.position(0); 
	}

    @Override
    public void onDrawFrame(GL10 gl) {
    	
//    	textY = 20;
//    	areaW = 1920;
//    	areaH = 80;
//    	textContent = "jlajdfljalfja";
//    	textSize = 30;
//    	textColor = Color.RED;
//    	bgColor = Color.WHITE;
//    	alpha = 100;
    	if(dataListener != null){
			dataListener.updateData();
			
			if(!dataListener.canWork()){
				return;
			}
		}
    	
    	if(isStopWork){
    		return;
    	}
    	
    	if(!drawString(textContent, textX, textY, (int)areaW, (int)areaH, textSize, textColor, bgColor, alpha)){
    		return;
    	}

    	gl.glClear(GL10.GL_COLOR_BUFFER_BIT| GL10.GL_DEPTH_BUFFER_BIT);
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();
        gl.glOrthof(0, areaW, 0, areaH, 1, -1);
        
        gl.glEnable(GL10.GL_TEXTURE_2D);

        //绑定纹理ID  
        if(textureId == 0){
        	textureId = loadTexture(gl);
        }else{
        	gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
        	
        	if(bitmap != null){
            	GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
            	gl.glTexParameterf(GL10.GL_TEXTURE_2D,
            			GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
            }
        }

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        gl.glVertexPointer(2, GL10.GL_FLOAT, 0, getVerticesBuffer(0, 0, areaW, areaH));

        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, getTextureBuffer());
        // gl.glRotatef(1, 0, 1, 0);  
        gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, 6, GL10.GL_UNSIGNED_SHORT, indices);
        
//        gl.glDisable(GL10.GL_TEXTURE_2D);
    }  
  
    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
    	Log.i(TAG, "gl change width = " + width + "; height = " + height);
    	
    	//设置场景大小  
        gl.glViewport(0, 0, width, height);
    }  
  
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    	drawString(" ", 0, 0, (int)areaW, (int)areaH, textSize, textColor, bgColor, alpha);
    	
    	textureId = loadTexture(gl);
    	isStopWork = false;
    }
    
    public void onDestroy(){
    	isStopWork = true;
    }
    
    public int loadTexture(GL10 gl) {
        int textureIds[] = new int[1];
        gl.glGenTextures(1, textureIds, 0);
        int textureId = textureIds[0];
        gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId);
        if(bitmap != null){
        	GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
        	gl.glTexParameterf(GL10.GL_TEXTURE_2D,
        			GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
        }
        gl.glTexParameterf(GL10.GL_TEXTURE_2D,
                GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST);
        gl.glBindTexture(GL10.GL_TEXTURE_2D, 0);
        return textureId;  
    }
    
    /** 
     * android中绘制字体，使用画布canvas 
     */ 
    public boolean drawString(String str, float x, float y, int areaW, int areaH, int fontsize, int color, int bgColor, int alpha){
    	if(bitmap != null){
    		bitmap.recycle();
    		bitmap = null;
    	}
//    	Log.i(TAG, "draw str = " + str);
    	
    	if((str == null) || "".equals(str)){
    		return false;
    	}
    	
        bitmap = Bitmap.createBitmap(areaW, areaH, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        //背景颜色  
        canvas.drawARGB(alpha, (bgColor>>16) & 0xFF, (bgColor>>8) & 0xFF, bgColor & 0xFF);
        
        Paint p = new Paint();
        
        p.setTextSize(fontsize);

        p.setColor(Color.BLACK);
        p.setStrokeWidth(3);
        p.setAntiAlias(true);
        p.setStyle(Style.FILL_AND_STROKE);
        p.setFakeBoldText(false);
        //paint.setShadowLayer(1, 0, 0, 0);
		
		canvas.drawText(str, x, y, p);
		
		//消除锯齿  
        p.setAntiAlias(true);  
        //字体为红色  
        p.setColor(color);
        p.setStrokeWidth(0);
        p.setStyle(Style.FILL_AND_STROKE);
        p.setFakeBoldText(false);
        //绘制字体  
        canvas.drawText(str, x, y, p);
        
        return true;
    }
    
    private FloatBuffer getVerticesBuffer(float x, float y, float w, float h){
    	ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * 2 * 4);
        byteBuffer.order(ByteOrder.nativeOrder());
        FloatBuffer vertices = byteBuffer.asFloatBuffer();
        
        vertices.put( new float[] {
        		x, y,
				x+w, y,
				x, y+h,
				x+w, y+h});
        
        vertices.position(0);
        
        return vertices;
    }
    
    private FloatBuffer getTextureBuffer(){
    	ByteBuffer textureBuffer = ByteBuffer.allocateDirect(4 * 2 * 4);
        textureBuffer.order(ByteOrder.nativeOrder());
        FloatBuffer texture = textureBuffer.asFloatBuffer();
        texture.put( new float[] { 0, 1f,  
                                    1f, 1f,  
                                    0f, 0f,  
                                    1f, 0f});  
        
        texture.position(0);
        
        return texture;
    }
}
